#include <stdio.h>
#include <string.h>

typedef struct _ast ast;
typedef struct _ast* past;

struct _ast
{
    int ivalue;
    char* svalue;
    char* nodeType;
    past left;
    past right;
};

// int genExpr(past node)
// {
//     if(node == NULL) return -1;
//     if(strcmp(node->nodeType, "expr") == 0)
//     {
//         char loperand[50]; char roperand[50]; char oper[5];

//         int ltype = genPrimaryExpr(node->left, loperand);
//         int rtype = genPrimaryExpr(node->right, roperand);

//         if(ltype == rtype && ltype != -1)
//         {
//             sprintf(oper, "%c", node->ivalue);
//             printf(" %d = %s %s %s\n", getTemVarNum(), loperand, oper, roperand);
//             return 1;
//         }
//     }
//     return -1;
// }

int genExpr(past node)
{
    if(node == NULL) return -1;
    if(strcmp(node->nodeType, "expr") == 0)
    {
        char loperand[50]; char roperand[50]; char oper[5];

        int ltype = genExpr(node->left);
        int rtype = genExpr(node->right);

        if(rtype == -1)//运算符右边无表达式
        {
            printf("ERROR: 发现错误的表达式");
            return -1;
        }
        else 
        {
            if(ltype == -1 && genPrimaryExpr(node->right, roperand) != -1)//运算符左边无表达式
            {
                sprintf(oper, "%c", node->ivalue);
                node->svalue = getTemVarNum();
                printf(" %d = %s %s\n", node->svalue, oper, roperand);
            }
            else if(genPrimaryExpr(node->left, loperand) != -1 && genPrimaryExpr(node->right, roperand) != -1)//左右都是基本表达式
            {
                sprintf(oper, "%c", node->ivalue);
                node->svalue = getTemVarNum();
                printf(" %d = %s %s %s\n", node->svalue, loperand, oper, roperand);
            }
            node->nodeType = "varRef";
            return 1;
        }
        return -1;
    }
    return 0;
}